//
//  UIs_CellFold_Cell.swift
//  APSwift
//
//  Created by jianbo.pei on 2022/12/10.
//

import UIKit
import Then

class UIs_CellFold_Cell: UITableViewCell {

    private var mainTitleLabel: UILabel!
    private var descLabel: UILabel!
    private var foldButton: UIButton!
    private var model: UIs_CellFold_Model?
    
    public var didTappedFoldButtonBlock: ((UIs_CellFold_Model) -> Void)?
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        createUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func createUI() {
        mainTitleLabel = UILabel().then({ make in
            contentView.addSubview(make)
            make.frame = CGRect(x: 16, y: 8, width: 300, height: 36)
            make.font(.boldSystemFont(ofSize: 20))
            make.textColor(.black)
        })
        
        descLabel = UILabel().then({ make in
            contentView.addSubview(make)
            make.numberOfLines = 0
            make.font(.systemFont(ofSize: 16))
            make.textColor(.lightText)
        })
        
        foldButton = UIButton(type: .custom).then({ make in
            contentView.addSubview(make)
            make.isHidden = true
            make.setTitleColor(.orange, for: .normal)
            make.titleLabel?.font(.boldSystemFont(ofSize: 25))
            make.addTarget(self, action: #selector(foldAction), for: .touchUpInside)
        })
    }
    
    @objc private func foldAction() {
        guard let model = self.model else { return }
        if model.foldStatus == .fold {
            model.foldStatus = .unfold
        } else {
            model.foldStatus = .fold
        }
        didTappedFoldButtonBlock?(model)
    }
    
    public func setup(with model: UIs_CellFold_Model) {
        self.model = model
        mainTitleLabel.text = model.title
        let style = model.style
        switch style {
        case .none:
            /// 没有描述，就不存在展开/收起按钮
            foldButton.isHidden = true
            if let attStr = model.unfoldAttributedString {
                descLabel.attributedText = attStr
                descLabel.frame = CGRect(x: 16, y: 44, width: 300, height: model.unfoldHeight)
            }
        case .hasFold:
            foldButton.isHidden = false
            descLabel.attributedText = model.unfoldAttributedString
            var descHeight = model.foldHeight
            var foldBtTitle = "展开"
            if model.foldStatus == .unfold {
                descHeight = model.unfoldHeight
                foldBtTitle = "收起"
            }
            descLabel.frame = CGRect(x: 16, y: 44, width: 300, height: descHeight)
            foldButton.setTitle(foldBtTitle, for: .normal)
            foldButton.frame = CGRect(x: 16, y: 44 + descHeight, width: 300, height: 50)
        }
    }
    
}
